from datetime import datetime
import os
from apscheduler.schedulers.background import BackgroundScheduler
from faiss import logger
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_apscheduler import APScheduler

db = SQLAlchemy()
from app.models import User
from pw import passwd
from flask import Flask
from flask_migrate import Migrate
from flask_cors import CORS
from flask_login import LoginManager
from app.tasks import TASK_FUNCTIONS

# 默认角色和对话设置
DEFAULT_SETTINGS = {
    "roles": [
        {"id": "default", "name": "AI助手", "description": "乐于助人的AI助手",
         "system_prompt": "你是一个乐于助人的AI助手"},
        {"id": "coder", "name": "编程专家", "description": "擅长编程和技术问题的AI",
         "system_prompt": "你是一个专业的程序员，擅长Python、Java等多种编程语言，能够帮助解决各种技术问题"},
        {"id": "writer", "name": "作家", "description": "创意写作和故事创作",
         "system_prompt": "你是一个富有创造力的作家，擅长各种文学体裁的创作"}
    ],
    "current_role": "default",
    "current_conversation": None,
    "conversations": {},
    "settings": {
        "max_tokens": 512,
        "temperature": 0.7,
        "top_p": 1.0,
        "presence_penalty": 0.0,
        "frequency_penalty": 0.0
    }
}

migrate = Migrate()
login = LoginManager()


# 登录成功后保存 user_id
# localStorage.setItem('user_id', response.data.user_id);
@login.user_loader
def load_user(user_id):
    return User.query.get(user_id)


def create_app(config_class=None):
    app = Flask(__name__)

    app.config[
        'SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://jun_test:{}@mysql2.sqlpub.com:3307/ws_data?charset=utf8mb4'.format(
        passwd)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
        'pool_size': 10,  # 连接池大小
        'max_overflow': -1,  # 无限连接溢出
        'pool_timeout': 30,  # 连接池连接超时时间
        'pool_recycle': 3600,  # 连接池连接的回收时间
    }
    with app.app_context():
        db.init_app(app)
        db.create_all()
        migrate.init_app(app, db)
        login.init_app(app)
        login.login_view = 'auth.login_page'
        CORS(app, supports_credentials=True)

        from app.routes import main_bp
        app.register_blueprint(main_bp)

        # 注册蓝图
        from app.routes.auth import bp as auth_bp
        app.register_blueprint(auth_bp, url_prefix='/api')

        from app.routes.conversations import bp as conv_bp
        app.register_blueprint(conv_bp, url_prefix='/api')

        from app.routes.roles import bp as roles_bp
        app.register_blueprint(roles_bp, url_prefix='/api')

        from app.routes.settings import bp as settings_bp
        app.register_blueprint(settings_bp, url_prefix='/api')

        from app.routes.iot import bp as iot_bp
        app.register_blueprint(iot_bp, url_prefix='/api')

        from app.routes.control import bp as control_bp
        app.register_blueprint(control_bp, url_prefix='/api')

        # 错误处理
        from app.errors import bp as errors_bp
        app.register_blueprint(errors_bp)

        from app.routes.job import bp as job_bp
        app.register_blueprint(job_bp, url_prefix='/api')

        from app.routes.cost import bp_cost as cost_bp
        app.register_blueprint(cost_bp, url_prefix='/api')

        app.jinja_env.filters['datetime'] = lambda dt: (
            dt.strftime('%Y-%m-%d %H:%M:%S') if isinstance(dt, datetime) else
            datetime.fromisoformat(dt).strftime('%Y-%m-%d %H:%M:%S') if isinstance(dt, str) else
            '未知'
        )

        scheduler = APScheduler()
        scheduler.init_app(app)

        from app.Ai_analyze.ai_function import analyze_data_task
        scheduler.add_job(
            id="job1",
            func=analyze_data_task,
            trigger="interval",
            seconds=300,
            replace_existing=True,
            max_instances=1
        )

        if not scheduler.running:
            scheduler.start()
            logger.info("调度器已启动")

        return app
